package com.attendancesystem.controller;


import com.attendancesystem.model.Course;
import com.attendancesystem.service.CourseService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;

@WebServlet(name = "UpdateCourseController", value = "/UpdateCourseController")
public class UpdateCourseController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
   protected void doPut(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        rep.setContentType("application/json;charset=UTF-8");
        JsonNode jsonNode = objectMapper.readTree(req.getReader());
        String courseId = req.getParameter("courseId");
        String courseCode = jsonNode.get("courseCode").asText();
        String courseName = jsonNode.get("courseName").asText();
        String credit = jsonNode.get("credit").asText();
        String teacher = jsonNode.get("teacher").asText();
        CourseService courseService = new CourseService();
        Course course=new Course();
        course.setCourseId(Integer.parseInt(courseId));
        course.setCourseCode(courseCode);
        course.setCourseName(courseName);
        course.setCredit(Integer.parseInt(credit));
        course.setTeacherId(teacher);
        boolean result = courseService.updateCourse(course);
        if (result){
            Writer writer = rep.getWriter();
            objectMapper.writeValue(writer, Collections.singletonMap("success", true));
        }else {
            rep.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }




    }
}
